package com.whacos.modules.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whacos.common.annotations.Log;
import com.whacos.common.controller.BaseController;
import com.whacos.common.enums.Constant;
import com.whacos.common.enums.DelFlagEnum;
import com.whacos.common.utils.BeanUtils;
import com.whacos.common.utils.StringUtils;
import com.whacos.common.vo.ResponseVO;
import com.whacos.modules.system.entity.Dict;
import com.whacos.modules.system.service.DictService;
import com.whacos.modules.system.vo.DictVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiongdun
 * @description SysDictController
 * @since 2018/11/17 17:11
 */
@Controller
@RequestMapping("/sys/dict")
@Slf4j
public class DictController extends BaseController {
    @Autowired
    private DictService dictService;

    // @Log("跳转字典信息列表")
    @GetMapping()
    @RequiresPermissions("sys:dict:dict")
    public String dict() {
        return "sys/dict/dict";
    }

    // @Log("获取字典信息列表")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("sys:dict:dict")
    public IPage<DictVO> list(DictVO dictVO) {
        // 查询列表数据
        IPage<DictVO> sysDictVOPage = new Page<>();
        try {
            // 请求参数
            // 查询数据
            IPage<Dict> sysDictPage = dictService.page(new Page<>(dictVO.getPageNum(), dictVO.getPageSize()),
                    Wrappers.lambdaQuery(new Dict())
                            .eq(StringUtils.isNotEmpty(dictVO.getName()), Dict::getKey, dictVO.getName())
                            .orderByAsc(Dict::getSortNum));
            // 返回结果
            BeanUtils.copyPage(sysDictPage, sysDictVOPage);
            List<DictVO> dictVOList = new ArrayList<>();
            sysDictPage.getRecords().forEach(source -> {
                DictVO target = new DictVO();
                BeanUtils.copyProperties(source, target);
                dictVOList.add(target);
            });
            sysDictVOPage.setRecords(dictVOList);
        } catch (Exception e) {
            log.error("查询字典列表异常，异常原因：" + e.getMessage(), e);
        }
        return sysDictVOPage;
    }

    // @Log("跳转新增字典信息页面")
    @GetMapping("/add")
    @RequiresPermissions("sys:dict:add")
    public String add() {
        return "sys/dict/add";
    }

    // @Log("跳转修改字典信息页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("sys:dict:edit")
    public String edit(@PathVariable("id") Long id, Model model) {
        Dict dict = dictService.getById(id);
        DictVO dictVO = new DictVO();
        BeanUtils.copyProperties(dict, dictVO);
        model.addAttribute("sysDict", dictVO);
        return "sys/dict/edit";
    }

    @Log("保存字典信息")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("sys:dict:add")
    public ResponseVO save(DictVO dictVO) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            Dict dict = new Dict();
            BeanUtils.copyProperties(dictVO, dict);
            // 保存结果
            dict.createdData(this.getUserId());
            dict.setDelFlag(DelFlagEnum.NORMAL.getValue());
            if (dictService.save(dict)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error(e.getMessage());
        }
        return ResponseVO.success();
    }

    @Log("修改字典信息")
    @ResponseBody
    @PostMapping("/update")
    @RequiresPermissions("sys:dict:edit")
    public ResponseVO update(DictVO dictVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            Dict dict = new Dict();
            BeanUtils.copyProperties(dictVO, dict);
            // 修改记录
            dict.updatedData(this.getUserId());
            if (dictService.updateById(dict)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            log.error("修改字典异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error(e.getMessage());
        }
        return ResponseVO.success();
    }

    @Log("删除字典信息")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("sys:dict:remove")
    public ResponseVO remove(Long id) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            if (dictService.removeById(id)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            log.error("删除字典异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error(e.getMessage());
        }
        return ResponseVO.success();
    }

    @Log("批量删除字典信息")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("sys:dict:batchRemove")
    public ResponseVO batchRemove(@RequestParam("ids[]") List<Long> ids) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            if (dictService.removeByIds(ids)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            log.error("批量删除字典异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error(e.getMessage());
        }
        return ResponseVO.success();
    }

    // @Log("查询字典信息所有的 type 列表")
    @GetMapping("/type")
    @ResponseBody
    public List<Dict> listType() {
        return dictService.listType();
    }

    // @Log("指定类别type增加字典信息")
    @GetMapping("/add/{type}/{description}")
    @RequiresPermissions("sys:dict:add")
    public String add(Model model,
                      @PathVariable("type") String type,
                      @PathVariable("description") String description) {
        model.addAttribute("type", type);
        model.addAttribute("description", description);
        return "sys/dict/add";
    }

    // @Log("按 type 查询字典信息")
    @ResponseBody
    @GetMapping("/list/{type}")
    public List<Dict> listByType(@PathVariable("type") String type) {
        // 查询列表数据
        return dictService.listByType(type);
    }
}
